/**
 * 客服系统 WebSocket 连接管理工具
 * 支持用户端和客服端两种连接模式
 */
import { API_BASE_URL } from '@/config/runtime'

const buildWsUrl = (path) => {
  const base = API_BASE_URL.endsWith('/') ? API_BASE_URL : `${API_BASE_URL}/`
  const relativePath = path.startsWith('/') ? path.slice(1) : path
  const url = new URL(relativePath, base)
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
  return url.toString()
}

class CustomerServiceWebSocket {
  constructor() {
    this.ws = null
    this.clientId = null
    this.clientName = null
    this.clientType = null // 'user' 或 'service'
    this.serviceId = null // 用户端需要绑定的客服ID
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectDelay = 3000
    this.isConnecting = false
    this.messageHandlers = new Set()
  }

  /**
   * 用户端连接
   * @param {string} userId - 用户ID
   * @param {string} userName - 用户名称
   * @param {string} serviceId - 客服ID（必填）
   */
  connectAsUser(userId, userName, serviceId) {
    if (!userId || !serviceId) {
      console.error('[客服WebSocket] 用户ID和客服ID不能为空')
      return false
    }

    this.clientId = userId
    this.clientName = userName || `用户${userId}`
    this.clientType = 'user'
    this.serviceId = serviceId
    this.isConnecting = true
    this.reconnectAttempts = 0

    try {
      // 用户端WebSocket端点：/connections/ws/user/{user_id}?name={name}&service_id={service_id}
      const wsUrl = buildWsUrl(`/connections/ws/user/${userId}?name=${encodeURIComponent(this.clientName)}&service_id=${serviceId}`)
      console.log(`[客服WebSocket] 用户端正在连接: ${wsUrl}`)
      
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log(`[客服WebSocket] 用户端连接成功: user_id=${userId}, service_id=${serviceId}`)
        this.isConnecting = false
        this.reconnectAttempts = 0
        this.onConnected()
      }

      this.ws.onmessage = (event) => {
        console.log(`[客服WebSocket] 收到消息:`, event.data)
        this.handleMessage(event.data)
      }

      this.ws.onerror = (error) => {
        console.error('[客服WebSocket] 连接错误:', error)
        this.isConnecting = false
      }

      this.ws.onclose = () => {
        console.log('[客服WebSocket] 用户端连接关闭')
        this.isConnecting = false
        this.ws = null
        
        // 自动重连
        if (this.clientId && this.serviceId && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++
          console.log(`[客服WebSocket] ${this.reconnectDelay/1000}秒后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
          setTimeout(() => {
            this.connectAsUser(this.clientId, this.clientName, this.serviceId)
          }, this.reconnectDelay)
        }
      }

      return true
    } catch (error) {
      console.error('[客服WebSocket] 连接异常:', error)
      this.isConnecting = false
      return false
    }
  }

  /**
   * 客服端连接
   * @param {string} serviceId - 客服ID
   * @param {string} serviceName - 客服名称
   */
  connectAsService(serviceId, serviceName) {
    if (!serviceId) {
      console.error('[客服WebSocket] 客服ID不能为空')
      return false
    }

    this.clientId = serviceId
    this.clientName = serviceName || `客服${serviceId}`
    this.clientType = 'service'
    this.isConnecting = true
    this.reconnectAttempts = 0

    try {
      // 客服端WebSocket端点：/connections/ws/service/{service_id}?name={name}
      const wsUrl = buildWsUrl(`/connections/ws/service/${serviceId}?name=${encodeURIComponent(this.clientName)}`)
      console.log(`[客服WebSocket] 客服端正在连接: ${wsUrl}`)
      
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log(`[客服WebSocket] 客服端连接成功: service_id=${serviceId}`)
        this.isConnecting = false
        this.reconnectAttempts = 0
        this.onConnected()
      }

      this.ws.onmessage = (event) => {
        console.log(`[客服WebSocket] 收到消息:`, event.data)
        this.handleMessage(event.data)
      }

      this.ws.onerror = (error) => {
        console.error('[客服WebSocket] 连接错误:', error)
        this.isConnecting = false
      }

      this.ws.onclose = () => {
        console.log('[客服WebSocket] 客服端连接关闭')
        this.isConnecting = false
        this.ws = null
        
        // 自动重连
        if (this.clientId && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.reconnectAttempts++
          console.log(`[客服WebSocket] ${this.reconnectDelay/1000}秒后尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
          setTimeout(() => {
            this.connectAsService(this.clientId, this.clientName)
          }, this.reconnectDelay)
        }
      }

      return true
    } catch (error) {
      console.error('[客服WebSocket] 连接异常:', error)
      this.isConnecting = false
      return false
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    console.log('[客服WebSocket] 手动断开连接')
    this.clientId = null
    this.clientName = null
    this.clientType = null
    this.serviceId = null
    this.reconnectAttempts = this.maxReconnectAttempts
    
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
    
    this.messageHandlers.clear()
  }

  /**
   * 发送消息（用户端发送给客服，客服端发送给用户）
   * @param {string} toUserId - 目标用户ID（客服端使用，用户端不需要）
   * @param {string} content - 消息内容
   */
  sendMessage(toUserId, content) {
    if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
      console.warn('[客服WebSocket] 连接未打开，无法发送消息')
      return false
    }

    let payload
    if (this.clientType === 'user') {
      // 用户端：发送给绑定的客服
      // 后端期望格式：{ "type": "chat", "content": "消息内容" }
      payload = {
        type: 'chat',
        content: content
      }
    } else if (this.clientType === 'service') {
      // 客服端：发送给指定用户
      // 后端期望格式：{ "to_user": "用户ID", "content": "消息内容" }
      payload = {
        to_user: toUserId,
        content: content
      }
    } else {
      console.error('[客服WebSocket] 未知的客户端类型')
      return false
    }

    try {
      this.ws.send(JSON.stringify(payload))
      console.log(`[客服WebSocket] 发送消息:`, payload)
      return true
    } catch (error) {
      console.error('[客服WebSocket] 发送消息失败:', error)
      return false
    }
  }

  /**
   * 添加消息处理器
   */
  onMessage(handler) {
    this.messageHandlers.add(handler)
    
    // 返回取消监听的函数
    return () => {
      this.messageHandlers.delete(handler)
    }
  }

  /**
   * 处理收到的消息
   */
  handleMessage(data) {
    try {
      let message
      try {
        message = JSON.parse(data)
      } catch {
        message = { type: 'text', content: data }
      }

      console.log('[客服WebSocket] 处理消息:', message)

      // 通知所有处理器
      this.messageHandlers.forEach(handler => {
        try {
          handler(message)
        } catch (error) {
          console.error('[客服WebSocket] 消息处理器执行失败:', error)
        }
      })
    } catch (error) {
      console.error('[客服WebSocket] 处理消息失败:', error)
    }
  }

  /**
   * 连接成功回调
   */
  onConnected() {
    console.log('[客服WebSocket] 连接已建立，可以接收消息')
  }

  /**
   * 获取连接状态
   */
  get isConnected() {
    return this.ws && this.ws.readyState === WebSocket.OPEN
  }
}

// 导出单例
export const customerServiceWS = new CustomerServiceWebSocket()

// 默认导出
export default customerServiceWS

